package com.chc.web.park_list.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chc.utils.Msg;
import com.chc.web.park_list.entity.ParkList;
import com.chc.web.park_list.entity.ParkListParm;
import com.chc.web.park_list.service.ParkListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/01/14/10:34
 * @Description: 车位管理模块
 */
@RestController
@RequestMapping("/api/parkList")
public class ParkListController {
    @Autowired
    private ParkListService parkListService;

    /**
     * 查询列表
     * */
    @GetMapping("/list")
    public Msg getList(ParkListParm parm){
        IPage<ParkList> list = parkListService.getList(parm);
        return Msg.success("查询成功",list);
    }

    /**
     * 新增车位
     * */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:parkList:add')")
    public Msg add(@RequestBody ParkList parkList){
        QueryWrapper<ParkList> query = new QueryWrapper();
        query.lambda().eq(ParkList::getParkName,parkList.getParkName());
        ParkList one = parkListService.getOne(query);
        if (one != null){
            return Msg.error("该车位已存在，不可重复添加!");
        }
        boolean save = parkListService.save(parkList);
        if(save){
            return Msg.success("新增车位成功!");
        }
        return Msg.error("新增车位失败!");
    }

    /**
     * 编辑车位
     * */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:parkList:edit')")
    public Msg edit(@RequestBody ParkList parkList){
        QueryWrapper<ParkList> query = new QueryWrapper();
        query.lambda().eq(ParkList::getParkName,parkList.getParkName());
        ParkList one = parkListService.getOne(query);
        if (one != null){
            return Msg.error("该车位已存在，请重新输入!");
        }
        boolean save = parkListService.updateById(parkList);
        if(save){
            return Msg.success("编辑车位成功!");
        }
        return Msg.error("编辑车位失败!");
    }

    /**
     * 删除车位
     * */
    @DeleteMapping("/{parkId}")
    @PreAuthorize("hasAuthority('sys:parkList:delete')")
    public Msg delete(@PathVariable("parkId") Long parkId){
        ParkList parkList = parkListService.getById(parkId);
        if (parkList.getParkStatus().equals("1")){
            return Msg.error("该车位正在被使用中，不可以删除");
        }
        boolean b = parkListService.removeById(parkId);
        if(b){
            return Msg.success("删除车位成功!");
        }
        return Msg.error("删除车位失败!");
    }


    //根据车位id查询车位列表
    @GetMapping("/listNoPage")
    public Msg getListNoPage(){
        List<ParkList> list = parkListService.list();
        return Msg.success("查询成功",list);
    }
}
